#!/usr/bin/env python

import os, sys, getopt
import httplib, time, threading



class Connection(threading.Thread):
    def __init__(self, host, port):
        threading.Thread.__init__(self)
        self.host = host
        self.port = port
        self.thread_stop = False
        self.time_usage = 0
        self.number_of_requests = 0


    def run(self):
        connection = httplib.HTTPConnection(self.host, self.port)
        while not self.thread_stop:
            start_time = time.time()
            connection.request("GET", "/")
            end_time = time.time()
            print connection.getresponse().read(),
            
            round_trip_time = end_time - start_time
            self.time_usage += round_trip_time
            self.number_of_requests += 1

            sleep_time = 1 - round_trip_time
            if sleep_time > 0:
                time.sleep(sleep_time)


    def stop(self):  
        self.thread_stop = True 



def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hr:n:p:")
    except getopt.GetoptError as err:
        print(err)
        sys.exit(2)

    # set default value
    request = 10
    host = "localhost"
    port = "80"

    for o, s in opts:
        # help information
        if o == "-h":
            print "usage:   -r    <requet sending frequency>"
            print "         -n    <host name>"
            print "         -p    <port number>"
            return
        elif o == "-r":
            request = int(s)
        elif o == "-n":
            host = s
        elif o == "-p":
            port = s

    # send requst by giving frequency
    connections = []
    for i in range(request):
        connection = Connection(host, port)
        connection.start()
        connections.append(connection)
    
    time.sleep(1600-1)
    time_usage = 0
    number_of_requests = 0
    for i in range(request):
        connections[i].stop()
        connections[i].join()
        time_usage += connections[i].time_usage
        number_of_requests += connections[i].number_of_requests
    print "Total time usage\t\tNumber of requests\t\tAverage request per time"
    print str(time_usage) + "\t\t\t" + str(number_of_requests) + "\t\t\t\t" + str(time_usage/number_of_requests)



if __name__ == "__main__":
    main(sys.argv)